package task4;

import java.math.BigInteger;

public class DoublingSequenceApp {
	private static final int DEFAULT_STEPS_NUMBER = 10;
	private static final int DEFAULT_THREADS_NUMBER = 10;

	public static void main(String[] args) {
		DoublingSequence ds = new DoublingSequence();

		System.out.println("*** SINGLE THREAD EXECUTION: ***");
		for (int i = 0; i < DEFAULT_STEPS_NUMBER; i++) {
			System.out.println(ds.next().toString());
		}

		ds.reset();
		System.out.println("\n\n*** MULTI THREAD EXECUTION: ***");
		Thread[] doublingThreads = new Thread[DEFAULT_THREADS_NUMBER];
		for (int i = 0; i < DEFAULT_THREADS_NUMBER; i++) {
			doublingThreads[i] = new Thread(ds.new DoublingThread(DEFAULT_STEPS_NUMBER));
		}
		for (int i = 0; i < DEFAULT_THREADS_NUMBER; i++) {
			doublingThreads[i].start();
		}
		
		for (int i = 0; i < DEFAULT_THREADS_NUMBER; i++) {
			try {
				doublingThreads[i].join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		System.out.println("*** RESULT SEQUENCE: ***");
		for(BigInteger bi : ds.resultSequence) {
			System.out.println(bi);
		}
		
		BigInteger bi = new BigInteger("2");
		for (int i = 0; i < DEFAULT_STEPS_NUMBER * DEFAULT_THREADS_NUMBER; i++) {
			if (!ds.resultSequence.contains(bi)) {
				System.out.println("MISSING STEP! " + bi.toString());
				break;
			}
			
			ds.resultSequence.remove(bi);
			bi = bi.multiply(new BigInteger("2"));			
		}
		if (!ds.resultSequence.isEmpty()) {
			System.out.println("DUPLICATES!");
		}
	}
}